package com.chen.pageProcessor;

import org.apache.commons.lang3.StringUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

public class TypeProcessor implements PageProcessor {
    private final Site site = Site.me().setRetryTimes(3).setSleepTime(900);

    private final DemoProcessor demoProcessor;

    public TypeProcessor(DemoProcessor demoProcessor) {
        this.demoProcessor = demoProcessor;
    }


    @Override
    public void process(Page page) {
        if (page.getRequest().getPriority() == -1) {
            List<String> all = page.getHtml().xpath("//div[@class=\"sl-v-list\"]/ul/li/a/@title").all();
            String url = page.getUrl().toString();
            for (String brand : all) {
                if (StringUtils.isEmpty(brand)) {
                    continue;
                }
                Request request = null;
                try {
                    request = getRequest(url, url + "&ev=exbrand_" + URLEncoder.encode(brand + "^", "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                request.setPriority(0);
                request.putExtra("brand", brand);
                request.putExtra("type", page.getRequest().getExtra("type"));
                page.addTargetRequest(request);
            }
        } else {
            demoProcessor.process(page);
        }
    }

    @Override
    public Site getSite() {
        return this.site;
    }

    public Request getRequest(String referer, String targetUrl) {
        Request request = new Request(targetUrl);
        request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        request.addHeader("Accept-Encoding", "gzip, deflate, br");
        request.addHeader("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
        request.addHeader("Connection", "keep-alive");
        request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0");
        request.addHeader("Host", "list.jd.com");
        request.addHeader("Pragma", "no-cache");
        request.addHeader("X-Requested-With", "XMLHttpRequest");
        request.addHeader("Referer", referer);
        request.putExtra("page", 1);
        request.putExtra("s", 1);
        request.putExtra("target", 500);
        request.setPriority(1);
        return request;
    }
}
